package com.example.wto.viewpagertest01;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wto on 4/25/2017.
 */

public class VpRoomFragement extends Fragment
{

    private String mTitle;
    private final static String BOUNDLE_TITLE="title";
    private Teacher teacher=new Teacher();
    private ParseHtml parseHtml=null;
    private ListView week_lv=null;
    private ImageView code_imgV=null;
    private AutoCompleteTextView teacher_id_auto_et=null;
    private EditText code_et=null;
    private String checkcode="";
    private Spinner termSpinner=null;
    private IUtilSql teacherSql=null;
    private List<TermBean> termList=new ArrayList<>();
    private TermAdapter termAdapter=null;
    private Button search_btn;
    private List<String> teacherNameList=new ArrayList<>();
    private TermBean termSelected=null;
    private List<TeacherBean> teacherBeanList=new ArrayList<>();
    private ArrayAdapter<String> teacherBeanAdapter=null;
    private CourseListAdapter courseListAdapter=null;
    private CollegeBean collegeBean;
    private UtilSqlHelper sqlHelper;
    private TextView collegeName;
    public VpRoomFragement()
    {
        super();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        collegeBean=new CollegeBean("0001","","http://jw.zzti.edu.cn");
        parseHtml=new ParseHtmlFactory().createParseHtml(collegeBean,ParseHtmlFactory.TEACHER);
        sqlHelper=new UtilSqlHelper(getActivity(),"test.db",null,1);

    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        Bundle bundle=getArguments();
        if(bundle!=null)
        {
            mTitle=bundle.getString(BOUNDLE_TITLE);
        }
        LinearLayout linearLayout=initView(inflater);
        initData();
        new OnLoadThread().start();
        return linearLayout;
    }

    public LinearLayout initView(LayoutInflater inflater)
    {
        //加载控件
        LinearLayout linearLayout=(LinearLayout) inflater.from(getContext()).inflate(R.layout.teacher_framgment_layout,null);
        teacher_id_auto_et=(AutoCompleteTextView) linearLayout.findViewById(R.id.teacher_id_edittext);
        code_et=(EditText)linearLayout.findViewById(R.id.code_edittext);
        week_lv=(ListView)linearLayout.findViewById(R.id.teacher_listview);
        code_imgV=(ImageView)linearLayout.findViewById(R.id.code_imagview);
        termSpinner=(Spinner)linearLayout.findViewById(R.id.term_spinner);
        search_btn=(Button)linearLayout.findViewById(R.id.id_search_btn);
        collegeName=(TextView)linearLayout.findViewById(R.id.id_college_name);
        return linearLayout;
    }
    public void initData()
    {
        //设置collegename
        collegeName.setText(collegeBean.getCollege_name());
        //初始化teacher
        teacher=new Teacher();
        //设置检索事件
        search_btn.setOnClickListener(new SearchBtnOnclickListener());
        //课程listview
        courseListAdapter=new CourseListAdapter(getContext(),R.layout.course_layout,teacher.getWeekList());
        week_lv.setAdapter(courseListAdapter);
        //学期下拉列表
        termAdapter=new TermAdapter(getContext(),R.layout.semester_item_layout,termList);
        termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        termSpinner.setAdapter(termAdapter);
        //
        //教师姓名自动匹配列表
        teacherNameList.clear();
        teacherNameList.addAll(Util.beanListToStringList(teacherBeanList));
        teacherBeanAdapter=new ArrayAdapter(getContext(),android.R.layout.simple_expandable_list_item_1,teacherNameList);
        teacher_id_auto_et.setAdapter(teacherBeanAdapter);
        teacher_id_auto_et.setThreshold(1);

        //学期监听事件
        termSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                termSelected=termList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });
    }
//当该frame加载到前台时，初始化网络数据
    class OnLoadThread extends Thread
    {
        @Override
        public void run()
        {

            List<TermBean> t = parseHtml.getIndex();
            if (parseHtml.getImage() != -1)
            {
                String imgPath = Environment.getExternalStorageDirectory() + File.separator +
                        "codeImage.jpg";
                final Bitmap bmp = BitmapFactory.decodeFile(imgPath);
                getActivity().runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        code_imgV.setImageBitmap(bmp);
                    }
                });

            }
            if (t != null)
            {

                termSelected = t.get(0);//初始化显示第一个学期信息
                termList.clear();
                termList.addAll(t);
                getActivity().runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        termAdapter.notifyDataSetChanged();
                    }
                });
                List<TeacherBean> tb = ((ParseTeacherHtml) parseHtml).getTeachers(termSelected
                        .getTermID());

                if (tb != null)
                {
                    teacherBeanList.clear();
                    teacherBeanList.addAll(tb);
                    teacherNameList.clear();
                    teacherNameList.addAll(Util.beanListToStringList(teacherBeanList));

                    getActivity().runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            teacherBeanAdapter.notifyDataSetChanged();
                        }
                    });

                }
            }
        }
    }
    public static VpRoomFragement newInstance(String title)
    {
        Bundle bundle=new Bundle();
        bundle.putString(BOUNDLE_TITLE,title);
        VpRoomFragement fragment=new VpRoomFragement();
        fragment.setArguments(bundle);
        return fragment;
    }

    class SearchBtnOnclickListener implements View.OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            final String semester_id=termSelected.getTermID();
            final String teacherName=teacher_id_auto_et.getText().toString();
            final String code=code_et.getText().toString();
            checkcode=code;
            if(teacherName.equals(""))
            {
                teacher.getWeekList().clear();
                courseListAdapter.notifyDataSetChanged();
                Toast toast=Toast.makeText(getActivity(),"请输入教师姓名",Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.show();
                return;
            }
            if(teacherNameList.contains(teacherName)==false)
            {
                teacher.getWeekList().clear();
                courseListAdapter.notifyDataSetChanged();
                Toast toast=Toast.makeText(getActivity(),"不存在该教师，请重新输入",Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.show();
                return;
            }
            int index=teacherNameList.indexOf(teacherName);
            final String teacher_id=teacherBeanList.get(index).getTeacherID();
            TeacherBean teacherBean=new TeacherBean();
            teacherBean.setCollege_id(collegeBean.getCollege_id());
            teacherBean.setS_id(semester_id);
            teacherBean.setTeacherID(teacher_id);
            teacherSql=new UtilTeacherSql(sqlHelper);
            Teacher tempTeacher=(Teacher) teacherSql.select(teacherBean);
            //如果数据库中有数据，则用数据库中的数据
            if(tempTeacher!=null)
            {
                teacher.getWeekList().clear();
                teacher.getWeekList().addAll(tempTeacher.getWeekList());
                courseListAdapter.notifyDataSetChanged();
                Log.i("tttttt", tempTeacher.toJsonObject());
            }
            else
            {
                new Thread()
                {
                    @Override
                    public void run()
                    {
                        if(code.equals(""))
                        {
                            teacher.getWeekList().clear();
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    courseListAdapter.notifyDataSetChanged();
                                    Toast toast=Toast.makeText(getActivity(),"请输入验证码",Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER,0,0);
                                    toast.show();
                                }
                            });

                            return;
                        }
                        Teacher t = ((ParseTeacherHtml)parseHtml).getTeacher(semester_id, teacher_id, code);
                        if(((ParseTeacherHtml)parseHtml).CODE_ERROR==1)
                        {
                            if(-1!=parseHtml.getImage())
                            {
                                teacher.getWeekList().clear();
                                String imgPath=Environment.getExternalStorageDirectory()+File.separator+"codeImage.jpg";
                                final Bitmap bmp= BitmapFactory.decodeFile(imgPath);
                                getActivity().runOnUiThread(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        Toast toast=Toast.makeText(getActivity(),"验证码错误，请重新输入",Toast.LENGTH_SHORT);
                                        toast.setGravity(Gravity.CENTER,0,0);
                                        toast.show();
                                        code_imgV.setImageBitmap(bmp);
                                        courseListAdapter.notifyDataSetChanged();
                                    }
                                });
                                return;
                            }

                        }
                        if (t != null)
                        {
                            Log.i("teacher", t.toJsonObject());

                            teacher.getWeekList().clear();
                            teacher.setBean(t.getBean());
                            teacher.getWeekList().addAll(t.getWeekList());
                            teacherSql.insert(teacher);
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    courseListAdapter.notifyDataSetChanged();
                                }
                            });
                        } else
                        {
                            teacher.getWeekList().clear();
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    Toast toast=Toast.makeText(getActivity(),"未找到这学期该教师的课程",Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER,0,0);
                                    toast.show();
                                    courseListAdapter.notifyDataSetChanged();
                                }
                            });

                        }
                    }
                }.start();
            }
        }
    }
}
